package com.test.service.impl;

import com.test.entity.Book;
import com.test.entity.Borrow;
import com.test.entity.User;
import com.test.entity.UserBorrowView;
import com.test.mapper.BorrowMapper;
import com.test.service.BorrowService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class BorrowServiceImpl implements BorrowService {

    @Resource
    private BorrowMapper borrowMapper;
    @Value("${location.bookService}")
    private String bookServiceLocation;
    @Value("${location.userService}")
    private String userServiceLocation;

    @Override
    public UserBorrowView getBorrowViewByUid(int uid) {
        List<Borrow> borrowList = borrowMapper.getBorrowsByUid(uid);
        // RestTemplate 支持多种方式的远程调用
        RestTemplate template = new RestTemplate();
        // 这里通过调用 getForObject 来请求其他服务，并将结果自动进行封装
        User user = template.getForObject("http://" + userServiceLocation + "/user/"+uid, User.class);
        List<Book> bookList = new ArrayList<>();
        borrowList.forEach(o -> bookList.add(template.getForObject("http://" + bookServiceLocation + "/book/"+o.getBid(), Book.class)));
        return new UserBorrowView(user, bookList);
    }
}
